'''
Clean up the database. Meant to be used during debugging only. Not for upload

@author: Tatiana Kichkaylo
'''

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from datamodel import *
import csv
import os

class InnerLoader(object):
  """
  Simplified version of data loader - no error checks, batching, or threads.
  This class should be used only during debugging. Not for upload
  """ 
  def __init__(self, kind, properties):
    self.__kind = kind
    self.__properties = properties
    
  def convert(self, values, key_name=None):
    properties = {'key_name': key_name}
    for (name, converter), val in zip(self.__properties, values):
      if converter is bool and val.lower() in ('0', 'false', 'no'):
          val = False
      properties[name] = converter(val)
    model_class = db.class_for_kind(self.__kind)
    entity = model_class(**properties)
    return entity
  
  def loadfile(self, filename):
    csv_file = open(filename, 'r')
    reader = csv.reader(csv_file, skipinitialspace=True)
    # Assume there is a header, don't even check
    reader.next()

    count = 0
    while True:
      try:
        row = reader.next()
        entity = self.convert(row)
        # print row, entity
        entity.put()
        count = count + 1
      except StopIteration:
        break
    # print 'Uploaded ', count, 'lines from', file
    return count
  
class CleanPage(webapp.RequestHandler):
  def __init__(self):
    self.__loaders = {}
    root = os.path.dirname(__file__)
    
    fname = str(root) + '/datamanagement/assettypes.csv'
    props = [('name', str), ('parentType', str), ('minCount', int), 
             ('maxCount', int), ('sortOrder', int)]
    self.__loaders[fname] = InnerLoader('AssetType', props)
        
    fname = str(root) + '/datamanagement/documenttypes.csv'
    props = [('name', str)]
    self.__loaders[fname] = InnerLoader('DocumentType', props)
    
  def get(self):
    self.response.out.write('Cleaner:<br/>')
    self.cleanAll()
    self.loadAll()
    self.response.out.write('<br/><hr/><a href="..">Back</a>')
    
  def cleanAll(self):
    """Clean the contents of the store completely"""
    toclean = ['AssetType', 'AssetInstance', 'DocumentType', 'DocumentPlace']
    for name in toclean:
      query = db.GqlQuery('SELECT * FROM ' + name)
      count = query.count()
      self.response.out.write('<br/>About to delete ' + str(count) + ' items from ' + name)
      if count > 0:
        result = query.fetch(count)
        for model in result:
          self.response.out.write('<br/>&nbsp;&nbsp;' + model.name)
          model.delete()
    
  def loadAll(self):
    for file, loader in self.__loaders.iteritems():
      count = loader.loadfile(file)
      self.response.out.write('<br/>Uploaded ' + str(count) + ' lines from ' + str(file))

application = webapp.WSGIApplication(
                                     [('/cleaner', CleanPage)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
  